<template>
  <div class="login-page">
    <el-card>
      <template #header>管理系统</template>
      <el-form
        :model="user"
        :rules="rules"
        label-width="100px"
        class="demo-ruleForm"
        ref="ruleForm"
      >
        <el-form-item prop="username" label="用户名">
          <el-input v-model="user.username" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="password" label="密码">
          <el-input
            show-password
            v-model="user.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login">提交</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { loginAPI } from '@/api/user'
export default {
  name: 'LoginIndex',
  data () {
    return {
      user: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '请输用户名', trigger: 'blur' },
          {
            min: 3,
            max: 5,
            message: '长度在 3 到 5 个字符',
            trigger: ['blur', 'change']
          }
        ],
        password: [
          { required: true, message: '请输密码', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    login () {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          // alert('成功')
          try {
            const res = await loginAPI(this.user)
            // localStorage.setItem('mj-pc-token', res.data.token)
            this.$store.commit('user/updateToken', res.data.token)
            // alert('登录成功')
            this.$message.success('登录成功')
            this.$router.push('/dashboard')
          } catch (e) {
            if (e.response) {
              this.$message.error(e.response.data.message)
            } else {
              this.$message.error('登录失败')
            }
          }
        }
      })
    },
    reset () {
      this.$refs.ruleForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  height: 100vh;
  background: url(@/assets/login-bg.svg) no-repeat center / cover;
  // element组件名就是类名
  .el-card {
    width: 420px;
    position: absolute;
    left: 50%;
    right: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    // #717cf8
    ::v-deep .el-card__header {
      text-align: center;
      background-color: #717cf8;
      height: 80px;
      color: #fff;
      line-height: 40px;
    }
    .el-form {
      padding: 0 20px;
    }
  }
}
</style>
